// server/api/studies/all.get.ts
import { defineEventHandler, getQuery, getHeader } from "h3";
import { verifyToken } from "../../utils/auth";
import prisma from "../../utils/prisma";

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, "authorization");
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      throw createError({ statusCode: 401, message: "未提供认证令牌" });
    }

    const token = authHeader.slice(7);
    const decoded = verifyToken(token);
    if (!decoded) {
      throw createError({ statusCode: 401, message: "令牌无效或已过期" });
    }

    // 获取查询参数
    const query = getQuery(event);
    const { 
      username, 
      type, // 可选：按学习类型过滤
      keyword, // 可选：按内容关键词搜索
      startDate, // 可选：开始日期筛选
      endDate // 可选：结束日期筛选
    } = query;

    if (!username) {
      throw createError({ statusCode: 400, message: "需要提供用户名参数" });
    }

    // 查找用户
    const user = await prisma.user.findUnique({
      where: { username: username as string },
    });

    if (!user) {
      throw createError({ statusCode: 404, message: "用户不存在" });
    }

    // 构建查询条件
    const whereCondition: any = { userId: user.id };

    // 类型筛选
    if (type && type !== 'all') {
      whereCondition.type = type;
    }

    // 关键词搜索
    if (keyword) {
      whereCondition.OR = [
        { content: { contains: keyword as string, mode: 'insensitive' } },
        { applicationScenario: { contains: keyword as string, mode: 'insensitive' } },
        { remark: { contains: keyword as string, mode: 'insensitive' } }
      ];
    }

    // 日期范围筛选
    if (startDate || endDate) {
      whereCondition.createdAt = {};
      
      if (startDate) {
        whereCondition.createdAt.gte = new Date(startDate as string);
      }
      
      if (endDate) {
        const end = new Date(endDate as string);
        end.setHours(23, 59, 59, 999); // 包含当天
        whereCondition.createdAt.lte = end;
      }
    }

    // 查询所有学习记录（不分页）
    const studies = await prisma.study.findMany({
      where: whereCondition,
      orderBy: { createdAt: "desc" },
      include: {
        user: {
          select: {
            username: true,
            email: true,
          },
        },
      },
    });

    console.log(`获取到全部 ${studies.length} 条学习记录，用户ID: ${user.id}`);

    return {
      code: 200,
      message: "获取全部学习记录成功",
      data: {
        studies,
        totalCount: studies.length,
        summary: {
          total: studies.length,
          byType: await getStudiesByType(user.id, whereCondition),
          recentCount: await getRecentStudiesCount(user.id)
        }
      },
    };
  } catch (error: any) {
    console.error("获取全部学习记录失败:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      message: error.message || "获取全部学习记录失败",
    });
  }
});

// 辅助函数：按类型统计
async function getStudiesByType(userId: number, whereCondition: any) {
  const studiesByType = await prisma.study.groupBy({
    by: ['type'],
    where: { userId, ...whereCondition },
    _count: {
      id: true
    }
  });
  
  return studiesByType.reduce((acc, item) => {
    acc[item.type] = item._count.id;
    return acc;
  }, {} as Record<string, number>);
}

// 辅助函数：获取最近7天的记录数
async function getRecentStudiesCount(userId: number) {
  const weekAgo = new Date();
  weekAgo.setDate(weekAgo.getDate() - 7);
  
  return await prisma.study.count({
    where: {
      userId,
      createdAt: {
        gte: weekAgo
      }
    }
  });
}